import { _decorator, Button } from 'cc';
import { BaseView } from '../../../../scripts/libs/rxjs/cc3/BaseView';
import { ReactiveProperty } from '../../../../scripts/libs/rxjs/cc3/ReactiveProperty';
import { BindButton } from '../../../../scripts/libs/rxjs/cc3/BindButton';
import { Label } from 'cc';
import { iap_sdk_m, IapProductInfo, ProvideInfo } from '../../../../scripts/managers/SDK/IapSDKManager';
import { lm } from '../../LobbyManager';
import { IapStat, udm } from '../../../../scripts/managers/UserDataManager';
import { thinking_sdk_m } from '../../../../scripts/managers/SDK/ThinkingCocosSDKManager';
import { timem } from '../../../../scripts/managers/TimeManager';
import { ReactiveCommand } from '../../../../scripts/libs/rxjs/cc3/ReactiveCommand';
import { ReactiveSet } from '../../../../scripts/libs/rxjs/cc3/ReactiveSet';
import { Timer } from '../../../../scripts/libs/rxjs/cc3/CreatorSchedule';
const { ccclass, property } = _decorator;

@ccclass('IapButtonItem')
export class IapButtonItem extends BaseView {

    data = ReactiveProperty.Create<IapProductInfo>(null);

    @property(Button)
    selfButton: Button = null;

    @property(Label)
    selfButtonLabel: Label = null;

    limitReason = ReactiveSet.Create<string>();

    beforeProvideCommand = ReactiveCommand.Create<ProvideInfo>();
    successCommand = ReactiveCommand.Create<ProvideInfo>();

    useObserves() {
        return [
            this.data.subscribe(this.refresh.bind(this)),
            BindButton(this.selfButton).subscribe(this.selfButtonClicked.bind(this)),
            this.limitReason.subscribe(this.limitReasonChanged.bind(this)),
        ];
    }

    refresh() {
        if (this.data.value == null) return;

        // this.selfButtonLabel.string = `${this.data.value.flag}: $${this.data.value.price / 100} ${JSON.stringify(this.data.value.provide)}`;
        if (this.selfButtonLabel != null) {
            this.selfButtonLabel.string = `$${this.data.value.price / 100}`;
        }

        // 购买限制
        let interactable = true;
        if (this.data.value.limited != null) {
            let stat = udm.iapStat.value[this.data.value.flag] as IapStat;
            if ((stat?.buyNum ?? 0) >= this.data.value.limited) {
                interactable = false;
            }
        }
        if (interactable) this.limitReason.delete('info_product_info_limit');
        else this.limitReason.add('info_product_info_limit');
    }

    limitReasonChanged() {
        if (this.limitReason.size > 0) {
            this.selfButton.interactable = false;
        } else {
            this.selfButton.interactable = true;
        }
    }

    selfButtonClicked() {
        if (this.data.value == null) return;
        this.log('@selfButtonClicked', JSON.stringify(this.data.value));

        if (this.data.value.limited != null) {
            let stat = udm.iapStat.value[this.data.value.flag] as IapStat;
            if ((stat?.buyNum ?? 0) >= this.data.value.limited) {
                lm.frontTipShow('Product buy times limited!');
                return;
            }
        }

        let iapStatItem = udm.iapStat.value[this.data.value.productId];
        if (iapStatItem == null) udm.iapStat.value[this.data.value.productId] = {};
        iapStatItem = udm.iapStat.value[this.data.value.productId];
        let BuyNum = iapStatItem.buyNum ?? 0;
        let RepeatTime = undefined;
        if (udm.iapBuyAt.value) {
            RepeatTime = (timem.now() - udm.iapBuyAt.value) / 1000 / 60;
        }

        udm.openWay.value = 'Store';
        udm.save();
        thinking_sdk_m.requestTrack('Shoping_Commodity_Click', {
            Commodity_ID: this.data.value.flag,
            GiftType: this.data.value.giftType,
            BuyNum,
            RepeatTime,
            Level_ID: udm.stageNum.value,
            DifficultyLevel: 0,
            OpenWay: udm.openWay.value,
            IsNew: udm.isNew.value,
            Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
        });

        lm.customLoadingReasons.add('purchase');

        iap_sdk_m.startPurchase(this.data.value).subscribe(_ => {

            lm.customLoadingReasons.delete('purchase');

            if (_?.status == 'success') {

                let iapStatItem = udm.iapStat.value[this.data.value.productId];
                if (iapStatItem == null) udm.iapStat.value[this.data.value.productId] = {};
                iapStatItem = udm.iapStat.value[this.data.value.productId];
                let BuyNum = iapStatItem.buyNum ?? 0;
                let RepeatTime = undefined;
                if (udm.iapBuyAt.value) {
                    RepeatTime = (timem.now() - udm.iapBuyAt.value) / 1000 / 60;
                }

                let Dill_ID = _.id ?? undefined;
                this.log('ShopIAPButtonItem Dill_ID', Dill_ID);

                iapStatItem.buyNum = BuyNum + 1;
                iapStatItem.buyAt = timem.now();
                udm.iapBuyAt.value = timem.now();
                udm.iapStat.value[this.data.value.productId] = iapStatItem;
                udm.iapStat.again();

                // gm.incCoinFlyCommand.execute({
                //     fromWorldPos: this.node.worldPosition,
                //     count: this.data.value.coin
                // });

                this.beforeProvideCommand.execute(this.data.value.provide);
                udm.provide(this.data.value.provide);

                thinking_sdk_m.requestSetSuperProperties({
                    CoinAll: udm.coin.value
                });

                // Timer(.2).subscribe(_ => { // 延迟打点是希望数据变动会导致的属性变化优先提交埋点，这样该iap埋点会包含变动之后数据
                thinking_sdk_m.requestTrack('Shoping_Commodity_Reward', {
                    Commodity_ID: this.data.value.flag,
                    GiftType: this.data.value.giftType,
                    BuyNum,
                    RepeatTime,
                    CommodityItem: iap_sdk_m.GetThinkingCommodityItem(this.data.value),
                    Dill_ID,
                    Level_ID: udm.stageNum.value,
                    Value: this.data.value.price,
                    DifficultyLevel: 0,
                    Commodity_State: 'Normal',
                    OpenWay: udm.openWay.value,
                    IsNew: udm.isNew.value,
                    Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
                });
                // });

                if (this.data.value.provide?.coin > 0) {
                    thinking_sdk_m.requestTrack('Coins_Get', {
                        CoinNum: this.data.value.provide?.coin,
                        Type: 'Gift',
                        Gift_Detail: this.data.value.flag,
                        IsNew: udm.isNew.value,
                        Level_ID: udm.stageNum.value,
                    });
                }

                if (this.data.value.provide?.swapper > 0) {
                    thinking_sdk_m.requestTrack('Item_Get', {
                        ItemType: 'swapper',
                        CType: 'Gift',
                        Gift_Detail: this.data.value.flag,
                        UseType: 'Num',
                        ItemNum: this.data.value.provide?.swapper,
                        ItemAll: udm.itemSwapper.value,
                        Level_ID: udm.stageNum.value,
                        IsNew: udm.isNew.value,
                        Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
                    });
                }
                if (this.data.value.provide?.magnet > 0) {
                    thinking_sdk_m.requestTrack('Item_Get', {
                        ItemType: 'magnet',
                        CType: 'Gift',
                        Gift_Detail: this.data.value.flag,
                        UseType: 'Num',
                        ItemNum: this.data.value.provide?.magnet,
                        ItemAll: udm.itemMagnet.value,
                        Level_ID: udm.stageNum.value,
                        IsNew: udm.isNew.value,
                        Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
                    });
                }
                if (this.data.value.provide?.balloon > 0) {
                    thinking_sdk_m.requestTrack('Item_Get', {
                        ItemType: 'balloon',
                        CType: 'Gift',
                        Gift_Detail: this.data.value.flag,
                        UseType: 'Num',
                        ItemNum: this.data.value.provide?.balloon,
                        ItemAll: udm.itemBalloon.value,
                        Level_ID: udm.stageNum.value,
                        IsNew: udm.isNew.value,
                        Booster_Itemdetail: `Swapper:${udm.itemSwapper.value}|Magnet:${udm.itemMagnet.value}|Balloon:${udm.itemBalloon.value}`
                    });
                }

                if (this.data.value.provide?.inf_heart_sec > 0) {
                    thinking_sdk_m.requestTrack('Get_Energy', {
                        Type: "Gift",
                        EnergyType: 'Time',
                        EnergyCount: this.data.value.provide?.inf_heart_sec / 3600,
                        IsNew: udm.isNew.value,
                        Level_ID: udm.stageNum.value,
                    });
                }

                this.successCommand.execute(this.data.value.provide);

            } else {
                lm.frontTipShow('Failed!');
            }
        });


    }



}

